package com.orangesale.cn.netrequest;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orangesale.cn.entity.OrangeUser;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUser {

    /**
     * 用户登录验证
     *
     * @param orangeUser
     */
    public OrangeUser userLogin(OrangeUser orangeUser) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        //数据类型为json格式
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        //将对象转为JSON字符串
        String jsonStr = JSONObject.toJSONString(orangeUser);
        RequestBody requestBody = RequestBody.create(jsonStr, mediaType);
        Request request = new Request.Builder()
                .url("http://172.16.40.55:8081/orange/user/login")
                .post(requestBody)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        JSONObject jsonObject = JSON.parseObject(response.body().string());
        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
        OrangeUser orangeUser1 = JSON.toJavaObject(jsonObject1, OrangeUser.class);
        return orangeUser1;
    }

    /**
     * 用户注册
     *
     * @param orangeUser
     * @return
     * @throws IOException
     */
    public boolean userRegister(OrangeUser orangeUser) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        //数据类型为json格式
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        //将对象转为JSON字符串
        String jsonStr = JSONObject.toJSONString(orangeUser);
        RequestBody requestBody = RequestBody.create(jsonStr, mediaType);
        Request request = new Request.Builder()
                .url("http://172.16.40.55:8081/orange/user/register")
                .post(requestBody)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        JSONObject jsonObject = JSON.parseObject(response.body().string());
        Log.i("register", "userRegister: "+jsonObject);
        return jsonObject.getBoolean("flag");
    }


}
